<template>
  <div class="wrap">
    <input type="text" placeholder="请输入问题" v-model="content" />
    <button @click="startStream">开始流式请求</button>
    <div class="output" v-html="message"></div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'

const md = new MarkdownIt()
const message = ref("");
const content = ref("你知道node.js吗");

const startStream = async () => {
  message.value = "";

  const url = `/api/ask?content=${encodeURIComponent(content.value)}`;
  const eventSource =  new EventSource(url);

  const handleChunk = (chunk) => {
      // 实时处理Markdown并防护XSS
      message.value += DOMPurify.sanitize(md.render(chunk));
    };

  eventSource.addEventListener("message", (e) => {
    const data = JSON.parse(e.data);
    console.log("data", data.done);
    if (data.done) {
      content.value = "";
      eventSource.close();
    } else {
      message.value += data.message.content;
    }
  });

  eventSource.addEventListener("end", () => {
    console.log("传输完成");
    eventSource.close();
  });

  eventSource.addEventListener("error", (e) => {
    console.error("传输异常:", e.data);
  });
};
</script>

<style>
.progress {
  color: #000;
  font-size: 20px;
  font-weight: 600;
}
body {
  background-color: #fff;
}
.output {
  width: 500px;
  /* height: 300px; */
  /* overflow: scroll; */
  white-space: pre-wrap;
  margin-top: 20px;
  border: 1px solid #999;
  padding: 10px;
  color: #000;
}
</style>
